﻿using IceDog.OTM.Server.Clients;
using Microsoft.AspNetCore.SignalR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace IceDog.OTM.Server.Hubs
{
    public class GameHub : Hub
    {
        private UserList _userList;
        public GameHub(UserList userList)
        {
            _userList = userList;
        }
        public async Task AddScore(int id, int score)
        {
            _userList.FirstOrDefault(n => n.ID == id).Score += score;
            await Clients.All.SendAsync("ReceiveRank", _userList);
        }

        public override Task OnConnectedAsync()
        {
            var id = _userList.MaxID;
            var user = new User()
            {
                ConnectionID = Context.ConnectionId,
                ID = id,
                Name = $"Player {id}"
            };
            _userList.Add(user);
            Clients.Caller.SendAsync("ReceiveUser", user, _userList).Wait();
            return base.OnConnectedAsync();
        }

        public override Task OnDisconnectedAsync(Exception exception)
        {
            var user = _userList.FirstOrDefault(u => u.ConnectionID != Context.ConnectionId);
            _userList.Remove(user);
            return base.OnDisconnectedAsync(exception);
        }
    }
}
